package com.huobao.yunying.activitys;

import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.view.sliding.AbSlidingTabView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.entity.Changed;
import com.huobao.yunying.entity.DetailCart_data;
import com.huobao.yunying.entity.DetailGoodsData;
import com.huobao.yunying.entity.Detail_images;
import com.huobao.yunying.entity.Detail_specs;
import com.huobao.yunying.entity.Detailprice_intervals;
import com.huobao.yunying.entity.Detailprops;
import com.huobao.yunying.entity.GouwucgeGoods;
import com.huobao.yunying.entity.Gouwuche_spec;
import com.huobao.yunying.entity.Gouwuche_specification;
import com.huobao.yunying.entity.Guige;
import com.huobao.yunying.fragments.Fragment_Guige_ListView;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.ImageUtils;
import com.huobao.yunying.utils.Utils;
import com.huobao.zhangying.R;
import com.xrz.sxm.base.dialog.BaseDialog;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选择规格数量
 *
 * @author Administrator
 */
public class Act_Select_GuigeAndNum extends HuobaoBaseActivity implements OnClickListener {

	@ViewInject(R.id.gouwuche_view)
	private View gouwuche_view;
	@ViewInject(R.id.tv_gouwuche_num)
	private TextView tv_gouwuche_num;

	// 商家logo
	@ViewInject(R.id.imageview)
	private ImageView imageview;
	// 商家名字
	@ViewInject(R.id.tv_title)
	private TextView tv_name;
	/**
	 * 批发数量的layout
	 */
	@ViewInject(R.id.llyt_guige)
	private LinearLayout llyt_guige;
	private DetailGoodsData goodsData;

	@ViewInject(R.id.tabview)
	private AbSlidingTabView mAbSlidingTabView;

	/**
	 * 选中的数量
	 */
	@ViewInject(R.id.tv_number)
	private TextView tv_number;
	/**
	 * 选中的价格
	 */
	@ViewInject(R.id.tv_price)
	private TextView tv_price;

	// 没有规格-------------------------------
	@ViewInject(R.id.llyt_noguige)
	private View noguige;// 没有规格是显示
	@ViewInject(R.id.tv_jia)
	private TextView tv_jia;
	@ViewInject(R.id.tv_jian)
	private TextView tv_jian;
	@ViewInject(R.id.tv_jiajian_number)
	private TextView tv_jiajian_number;
	@ViewInject(R.id.tv_jiageandkucun)
	private TextView tv_jiageandkucun;// 价格喝库存

	@ViewInject(R.id.btn_1)
	private TextView btn_1;

	// 购物车数量
	private String gouwucheNum;

	private GouwucgeGoods goods;
	private String goodsid;

	//true:点击的是立即订购
	private boolean isQuit;
	@Override
	protected int getContentView() {
		return R.layout.layout_guigeandnum;
	}

	@Override
	protected String getTitleText() {
		return "选择商品规格和数量";
	}

	@Override
	protected void init() {
		EventBus.getDefault().register(this);
		goodsData = (DetailGoodsData) getIntent().getSerializableExtra("data");
		goodsid = getIntent().getStringExtra("goodsid");
		isQuit = getIntent().getBooleanExtra("isQuit",false);
		if(isQuit){
			btn_1.setText("结算");
		}
		gouwucheNum = getIntent().getStringExtra("gouwuche");
		goods = (GouwucgeGoods) getIntent().getSerializableExtra("gouwucheGoods");
		tv_gouwuche_num.setText(gouwucheNum);
		if (goodsid == null) {
			gouwuche_view.setVisibility(View.VISIBLE);
			initData();
		} else {

			gouwuche_view.setVisibility(View.GONE);
			mAbTitleBar.setTitleText("修改商品规格和数量");
			btn_1.setText("提交修改");
			tv_number.setText("总计共" + goods.quantity + "件");
			tv_price.setText("￥" + Utils.get2point((goods.quantity * Double.parseDouble(goods.price))));
			getDetail(goodsid);
		}
		gouwuche_view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, Act_Main.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				EventBus.getDefault().post("2", "ShowGouwuche");
				startActivity(intent);
				finish();
			}
		});
		btn_1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
					onPutGouwuche();

			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	private void initData() {
		showGuige();
		ImageUtils.loadimg(imageview, goodsData.default_image);
		tv_name.setText(goodsData.goods_name);

		if (goodsData._spec_arr.size() == 0) {
			mAbSlidingTabView.setVisibility(View.GONE);
			noguige.setVisibility(View.VISIBLE);
			showNoGuige();
		} else {
			mAbSlidingTabView.setVisibility(View.VISIBLE);
			noguige.setVisibility(View.GONE);
			showBar();
		}
	}

	private void showNoGuige() {
		tv_jiageandkucun.setText("价格" + goodsData.price + "(库存" + goodsData._stock + goodsData.unit + ")");
		tv_jia.setOnClickListener(this);
		tv_jian.setOnClickListener(this);
		tv_jiajian_number.setOnClickListener(this);
	}

	private void showBar() {
		// 缓存数量
		mAbSlidingTabView.getViewPager().setOffscreenPageLimit(5);
		mAbSlidingTabView.setTabTextColor(Color.BLACK);
		mAbSlidingTabView.setTabSelectColor(Color.rgb(30, 168, 131));
		mAbSlidingTabView.setTabBackgroundResource(R.drawable.tab_bg);
		mAbSlidingTabView.setTabLayoutBackgroundResource(R.mipmap.slide_top);
		mAbSlidingTabView.setTabPadding(20, 8, 20, 8);
		List<String> tabTexts = new ArrayList<String>();
		List<Gouwuche_specification> specification = null;
		if (goods != null) {
			specification = goods.specification;
		}

		List<Fragment> mFragments = new ArrayList<Fragment>();
		for (int i = 0; i < goodsData._spec_arr.size(); i++) {
			String str = goodsData._spec_arr.get(i);
			tabTexts.add(str);
			List<List<String>> list = goodsData._spec_json.get(i);
			String spec_id = list.get(0).get(3);
			if (goods != null) {
				Gouwuche_specification specification2 = null;
				for (int k = 0; k < specification.size(); k++) {
					if (specification2 != null)
						break;
					Gouwuche_specification sp = specification.get(k);
					if (sp.spec_id.equals(spec_id)) {
						specification2 = sp;
						break;
					}
				}
				if (specification2 != null) {
					for (Gouwuche_spec spec : specification2.spec) {
						if (mapChange.containsKey(spec.spec_id)) {
							int p = mapChange.get(spec.spec_id);
							p += spec.num;
							mapChange.put(spec.spec_id, p);
						} else {
							mapChange.put(spec.spec_id, spec.num);
						}
					}
					mFragments.add(Fragment_Guige_ListView.getInstant(createGuige(goodsid, list,  specification2.spec)));
				} else {
					mFragments.add(Fragment_Guige_ListView.getInstant(createGuige(goodsid, list,  null)));
				}
			} else {
				mFragments.add(Fragment_Guige_ListView.getInstant(createGuige(goodsid, list,  null)));
			}
		}
		mAbSlidingTabView.addItemViews(tabTexts, mFragments);
		mAbSlidingTabView.setTabPadding(20, 8, 20, 8);
	}

	private Guige createGuige(String goodsid, List<List<String>> list, List<Gouwuche_spec> _specs) {
		Guige guige = new Guige();
		guige.goodsid = goodsid;
		guige.list = list;
		guige._specs = _specs;
		return guige;
	}

	private Map<String, Integer> mapChange = new HashMap<String, Integer>();
	private onPriceChangedListener listener = new onPriceChangedListener() {
		@Override
		public void onChanged(float change, int numChange, String type) {
			changePrice(change, numChange, type);
		}
	};

	private void changePrice(float change, int numChange, String type) {
//		if (numChange == -1) {
//			if (mapChange.containsKey(type)) {
//				int num = mapChange.get(type);
//				num--;
//				mapChange.put(type, num);
//			}
//		} else if(numChange == 1) {
//			if (mapChange.containsKey(type)) {
//				int num = mapChange.get(type);
//				num++;
//				mapChange.put(type, num);
//			} else {
//				mapChange.put(type, 1);
//			}
//		}else{
			if (mapChange.containsKey(type)) {
				int num = mapChange.get(type);
				num+= numChange;
				mapChange.put(type, num);
			} else {
				mapChange.put(type, numChange);
			}
//		}
		double price = Double.parseDouble(tv_price.getText().toString().trim().replaceAll("￥", ""));
		int num = Integer.parseInt(tv_number.getText().toString().trim().replaceAll("总计共", "").replaceAll("件", ""));
		price += change;
		num += numChange;
		tv_number.setText("总计共" + num + "件");
		double onePrice = getOneprice(num);
		if(onePrice == 0){
			tv_price.setText("￥" + Utils.get2point((price)));
		}else{
			tv_price.setText("￥" + Utils.get2point((onePrice * num)));
		}
	}

	@Subscriber(tag = "onPriceChanged")
	public void onPriceChanged(Changed ch){
		changePrice(ch.getChange(), ch.getNumChange(), ch.getType());
	}
	/**
	 * 获取单件价格
	 *
	 * @return
	 */
	private double getOneprice(int num) {
		double price = 0;
		for (Detailprice_intervals intervals : goodsData.price_intervals) {
			// if (intervals.max_count == 0) {
			// return Float.parseFloat(intervals.price);
			// }
			// if (num >= intervals.min_count && num <= intervals.max_count)
			// return Float.parseFloat(intervals.price);
			if (num >= intervals.min_count)
				price = Double.parseDouble(intervals.price);
		}
		if (price == 0) {
			if (goodsData.price_intervals != null && goodsData.price_intervals.size() != 0) {
				price = Double.parseDouble(goodsData.price_intervals.get(0).price);
			} else {
				return 0;
			}
		}

		return price;
	}

	/**
	 * 显示规格
	 */
	private void showGuige() {
		llyt_guige.removeAllViews();
		if (goodsData.price_intervals_count.equals("0")) {
			View view = LayoutInflater.from(context).inflate(R.layout.item_guige, null);
			TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
			TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
			tv_number.setText("≥ 1 " + goodsData.unit);
			try{
				tv_price.setText("￥" + goodsData.price+"--"+"￥"+goodsData._spec_json.get(0).get(goodsData._spec_json.get(0).size()-1).get(1));
			}catch(Exception e){
				tv_price.setText("￥" + goodsData.price);
			}
			llyt_guige.addView(view);
		} else {
			for (Detailprice_intervals intervals : goodsData.price_intervals) {
				View view = LayoutInflater.from(context).inflate(R.layout.item_guige, null);
				TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
				TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
				if (intervals.max_count == 0) {
					tv_number.setText("≥ " + intervals.min_count + goodsData.unit);
				} else {
					tv_number.setText(intervals.min_count + "-" + intervals.max_count + goodsData.unit);
				}
				tv_price.setText("￥" + intervals.price);
				llyt_guige.addView(view);
			}
		}
	}

	public interface onPriceChangedListener {
		/**
		 * @param change    价格变动（正负）
		 * @param numChange (数量变动)
		 */
		void onChanged(float change, int numChange, String type);
	}

	@Override
	public void onClick(View v) {
		String str = tv_jiajian_number.getText().toString().trim();
		int oldNum = Integer.parseInt(str);
		switch (v.getId()) {
			case R.id.tv_jia:
				if (oldNum < Integer.parseInt(goodsData._stock)) {
					oldNum++;
				}
				break;
			case R.id.tv_jian:
				if (oldNum > 0)
					oldNum--;
				break;
			case R.id.tv_jiajian_number:
				BaseDialog.showEditTextDialog(context, oldNum, Integer.parseInt(goodsData._stock), new BaseDialog.OnDialogSelectListener() {
					@Override
					public void onSelect(String input) {
						int num = Integer.parseInt(input);
						showPrice(num);
					}
				});
				break;
		}

		showPrice(oldNum);
	}

	private void showPrice(int oldNum) {
		double onePrice = getOneprice(oldNum);
		double allPrice = onePrice * oldNum;
		tv_price.setText("￥" + Utils.get2point(allPrice));
		tv_number.setText("总计共" + oldNum + "件");
		tv_jiajian_number.setText(oldNum + "");
	}


	/**
	 * 放入购物车
	 */
	private void onPutGouwuche() {
		List<Detailprice_intervals> price_intervals = goodsData.price_intervals;
		int minCount = 0;
		if (price_intervals == null || price_intervals.size() == 0) {
			minCount = 1;
		} else {
			minCount = price_intervals.get(0).min_count;
		}
		Map<String, String> map;
		List<List<List<String>>> _spec_json = goodsData._spec_json;
		String spec_id_js,quantity_js;
		if (goodsData._spec_arr == null || goodsData._spec_arr.size() == 0) {
			String id = _spec_json.get(0).get(0).get(3);
			String num = tv_jiajian_number.getText().toString().trim();
			spec_id_js = id;
			quantity_js = num;
			if (Integer.parseInt(num) < minCount) {
				Toast.makeText(context, "购买数量不能低于起批量", Toast.LENGTH_SHORT).show();
				return;
			}
			map = HttpUtil.getParams(HttpConst.FRIST_KEY, "cart", HttpConst.SECOND_KEY, "add", "id", goodsData.goods_id,
					"spec_id", id, "quantity", num);
		} else {
			int allCount = 0;
			StringBuffer sb_spec_id = new StringBuffer();
			StringBuffer sb_quantity = new StringBuffer();
			for (Map.Entry<String, Integer> entry : mapChange.entrySet()) {
				sb_spec_id.append(entry.getKey());
				sb_spec_id.append(",");
				allCount += entry.getValue();
				sb_quantity.append(entry.getValue() + "");
				sb_quantity.append(",");
			}
			if (allCount < minCount) {
				Toast.makeText(context, "购买数量不能低于起批量", Toast.LENGTH_SHORT).show();
				return;
			}
			String spec_id = sb_spec_id.toString().substring(0, sb_spec_id.toString().length() - 1);
			String quantity = sb_quantity.toString().substring(0, sb_quantity.toString().length() - 1);
			spec_id_js = spec_id;
			quantity_js = quantity;
			if (goodsid != null) {
				map = HttpUtil.getParams(HttpConst.FRIST_KEY, "cart", HttpConst.SECOND_KEY, "submitedit", "id",
						goodsData.goods_id, "spec_id", spec_id, "quantity", quantity);
			} else
				map = HttpUtil.getParams(HttpConst.FRIST_KEY, "cart", HttpConst.SECOND_KEY, "add", "id",
						goodsData.goods_id, "spec_id", spec_id, "quantity", quantity);
		}

		if(isQuit){
			Intent intent = new Intent(this, Act_Jiesuan.class);
			intent.putExtra("isQuit", true);
			intent.putExtra("store_id", goodsData.store_id);
			intent.putExtra("id",goodsData.goods_id);
			intent.putExtra("spec_id",spec_id_js);
			intent.putExtra("quantity",quantity_js);
			startActivity(intent);
			finish();
			return;
		}
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				String msg = jsonObject.getString("msg");
				if (msg.equals("")) {
					Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();

				} else
					Toast.makeText(context, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
				EventBus.getDefault().post("", "editGouwucheSuccess");
				finish();
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	private void getDetail(String goodsId) {
		Map<String, String> map = HttpUtil.getParams(HttpConst.FRIST_KEY, "goods", "id", goodsId);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				jsonObject = jsonObject.getJSONObject("retval");
				JSONObject good_data = jsonObject.getJSONObject("good_data");
				goodsData = JSON.parseObject(good_data.toString(), DetailGoodsData.class);
				goodsData.price_intervals = JSON.parseArray(good_data.getString("price_intervals"),
						Detailprice_intervals.class);
				goodsData._specs = JSON.parseArray(good_data.getString("_specs"), Detail_specs.class);
				goodsData._images = JSON.parseArray(good_data.getString("_images"), Detail_images.class);
				goodsData.props = JSON.parseArray(good_data.getString("props"), Detailprops.class);
				goodsData._spec_arr = JSON.parseArray(good_data.getString("_spec_arr"), String.class);

				List<List<List<String>>> lists = new ArrayList<List<List<String>>>();
				JSONArray _spec_json = good_data.getJSONArray("_spec_json");
				for (int i = 0; i < _spec_json.size(); i++) {
					JSONArray array = _spec_json.getJSONArray(i);
					List<List<String>> l = new ArrayList<List<String>>();
					for (int j = 0; j < array.size(); j++) {
						JSONArray jsonArray = array.getJSONArray(j);
						List<String> list = JSON.parseArray(jsonArray.toString(), String.class);
						l.add(list);
					}
					lists.add(l);
				}
				goodsData._spec_json = lists;

				// JSONObject store_data =
				// jsonObject.getJSONObject("store_data");
				// storeData = JSON.parseObject(store_data.toString(),
				// DetailStoreData.class);
				//
				JSONObject cart_data = jsonObject.getJSONObject("cart_data");
				DetailCart_data cartData = JSON.parseObject(cart_data.toString(), DetailCart_data.class);
				tv_gouwuche_num.setText(cartData.cart_num);
				// showDetail();
				initData();
			}

			@Override
			public void onHttpError(String error) {
				finish();
			}
		});
	}
}
